package com.ruge.core.config;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import com.ruge.core.serializer.PrivacySerializerNameFilter;
import com.ruge.core.serializer.PrivacySerializerValueFilter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * description: SerializerConfig
 * create time at 2022/6/6 22:30
 *
 * @author alice.ruge
 * @since 0.0.3
 */
@Configuration
public class SerializerConfig {
    @Bean
    public HttpMessageConverters customConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        //1.定义一个converters转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastjson的配置信息，比如: 是否需要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setCharset(StandardCharsets.UTF_8);
        //添加自己写的拦截器
        fastJsonConfig.setWriterFilters(new PrivacySerializerNameFilter(), new PrivacySerializerValueFilter());
        fastJsonConfig.setWriterFeatures(JSONWriter.Feature.PrettyFormat);
        fastJsonConfig.setWriterFeatures(JSONWriter.Feature.WriteClassName);
        fastJsonConfig.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue);
        fastJsonConfig.setWriterFeatures(JSONWriter.Feature.WriteEnumsUsingName);
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        //3.在converter中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        converters.add(0, fastConverter);
        return new HttpMessageConverters(converters);
    }
}
